#!/usr/bin/env python
# coding: utf-8

'''文件上传'''

import tornado.web
import tornado.httpserver
import tornado.ioloop
from tornado.web import url, RequestHandler
import codecs

class IndexHandler(RequestHandler):
    def get(self, *args, **kwargs):
        print("index")
        self.write("index")

class UploadHandler(RequestHandler):
    def post(self):
        '''
        POST /upload/
        body:
        img: 图片
        xcode： 'y'
        txt: 文本文件
        返回一个字典，不包含非文件上传的字段
        {
            'img': [{'filename': '选区_001.png', 'body':b'二进制数据'}],
            'txt': [{'filename': '学习路标', 'body': b'文本字节编码'}]
        }
        '''
        payload = self.request.files
        for name, contents in payload.items():
            if payload.get(name):
                with codecs.open(contents[0]['filename'], 'w', encoding='gbk') as f:
                    f.write(contents[0]['body'].decode('gbk'))
        self.write("ok")

if __name__ == "__main__":
    app = tornado.web.Application([
        url(r'/', IndexHandler, name='index'),
        url(r'/upload/', UploadHandler, name='upload')
    ])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.bind(8000)
    http_server.start(1)   #1：开启一个进程, 0：有多少个cpu核心就开启多少个进程
    tornado.ioloop.IOLoop.current().start()

